﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
    /// <summary>
    /// 采购订单 OA 操作
    /// </summary>
    [Description("销售发票审核推送小满(普通发票和增值税专用发票)"), HotUpdate]
    public class InvoiceAudit : AbstractOperationServicePlugIn
    {
        public string btype = "销售发票审核推送小满";
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string logType = "销售发票审核推送小满";
        public TokenData TokenObj = null;
        public string xmUserUrl = $@"https://api-sandbox.xiaoman.cn/v1/user/list";
        public string url { get; set; } = "https://api-sandbox.xiaoman.cn/v1/invoices/receipt/push";
        Dictionary<string, string> headers = new Dictionary<string, string>() ;
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            try
            {
                List<int> IdList = e.DataEntitys.Select(x => x["Id"].ToStringV1().ToInt32V1()).Distinct().Where(y => y != 0).ToList();
                if (IdList == null|| IdList.Count<1)
                    return;
                var tokens = PostHelper.GetToken(logType);
                if (!tokens.Item1)
                {
                    LogHelper.XiaoManLog($"【获取token错误】【msg:{tokens.Item2.msg}】", logType);
                    return;
                }
                TokenObj = tokens.Item2;
                Main(IdList);
            }
            catch (Exception ex)
            {
                LogHelper.XiaoManLog($"【异常FPD2001】\n【msg:{ex.Message}】", logType);
                return;
            }
        }

        public void Main(List<int> IdList)
        {
            List<SalInvoice> dataList = new List<SalInvoice>();
            //分次查询
            int size = 5000;
            int icount = IdList.Count <= size ? 1 : IdList.Count % size > 0 ? IdList.Count / size + 1 : IdList.Count / size;
            for (int i = 0; i < icount; i++)
            {
                List<int> ids = IdList.Skip(i * size).Take(size).ToList();
                string sql = $@"/*dialect*/ select 
id=main.FID
,billNo=main.FBILLNO  --发票单号
,ser=enty.FSEQ
,entyId=enty.FENTRYID
,hkdId=enty.FXMHKDID  --小满汇款单ID
,salXMId=sal.FXMID --销售订单小满ID
,salNo=enty.FSALESORDERNO --销售订单号
,deliveredAmount=ISNULL((select SUM(sentyF.FAMOUNT_LC) from T_SAL_ORDERENTRY senty
inner join T_SAL_ORDERENTRY_F sentyF on senty.FENTRYID=sentyF.FENTRYID
where senty.FID=sal.FID),0)  --已发货金额
,date=main.FDATE --业务日期
,currency='CNY' --币别
,amount=entyO.FNOTAXAMOUNT --不含税金额本位币
,type='L'  --类型
,exchangeRate=1  --汇率
,remarks=enty.FCOMMENT --备注
from T_IV_SALESICENTRY enty
left join T_IV_SALESICENTRY_O entyO on enty.FENTRYID=entyO.FENTRYID
left join T_IV_SALESIC main on enty.FID=main.FID
left join T_SAL_ORDER sal on sal.FBILLNO=enty.FSALESORDERNO
where ISNULL(enty.FSALESORDERNO,'')<>''
and ISNULL(sal.FID,0)<>0
and ISNULL(sal.FXMID,'')<>''
and main.FID in ({string.Join(",", ids)})
";
                DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(Context, sql);
                List<SalInvoice> pList = datas.DynamicObjectCollectionToDataList<SalInvoice>();
                dataList.AddRange(pList);
            }
            if (dataList.Count < 1)
                return;
         
            {
                Dictionary<string, List<SalInvoice>> dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
                headers = new Dictionary<string, string>();
                headers.Add("Authorization", $@"Bearer {TokenObj.token}");
                foreach (var dic in dataDic)
                {
                    List<SalInvoice> valueList = dic.Value;
                    //SalInvoice firstData = valueList.FirstOrDefault();
                    foreach (SalInvoice data in valueList)
                    {
                        try
                        {
                            string json = string.Empty;
                            {
                                JObject MainObj = new JObject();
                                if (!data.hkdId.IsNullOrEmptyOrWhiteSpace())
                                    MainObj["cash_collection_id"] = data.hkdId;

                                MainObj["order_id"] = data.salXMId;
                                MainObj["collection_date"] = data.date;
                                MainObj["currency"] = data.currency;
                                MainObj["amount"] = data.amount;
                                MainObj["type"] = data.type;
                                MainObj["exchange_rate"] = data.exchangeRate;
                                MainObj["comment"] = data.remarks;
                                MainObj["collect_status"] = 1;
                                json = MainObj.ToStringV1();
                            }
                            string inContent = $"【{data.billNo}】【{data.ser}】【{data.entyId}】【销售发票】【地址：{url}】\n【header:{JsonConvert.SerializeObject(headers)}】\n【传入内容：{json}】";
                            LogHelper.XiaoManLog(inContent, logType);
                            string reponse = PostHelper.Post(url, json, headers);
                            string outContent = $"【{data.billNo}】【{data.ser}】【{data.entyId}】【销售发票】【返回内容：{reponse}】";
                            LogHelper.XiaoManLog(outContent, logType);
                            //解析返回数据
                            JObject reObj = JsonConvert.DeserializeObject<JObject>(reponse);
                            if (reObj["code"].ToStringV1().EqualsV1("200") && reObj["message"].ToStringV1().EqualsV1("success"))
                            {
                                //推送销售发票成功
                                JObject dataObj = JsonConvert.DeserializeObject<JObject>(reObj["data"].ToStringV1());
                                string xmid = dataObj["cash_collection_id"].ToStringV1();
                                DBUtils.Execute(Context, $@"update T_IV_SALESICENTRY set FXMHKDID='{xmid}' where FENTRYID={data.entyId}");
                                InitMessage(true, data.id.ToStringV1(), data.billNo, $"第{data.ser}行推送小满完成");
                            }
                            else
                            {
                                InitMessage(false, data.id.ToStringV1(), data.billNo, $"第{data.ser}行推送小满失败\n错误信息：{reponse}");
                            }
                        }
                        catch (Exception ex)
                        {

                            LogHelper.XiaoManLog($"异常【FP1005】【单号：{data.billNo} 行号：{data.ser} 明细ID：{data.entyId} 销售订单号：{data.salNo}】\n【msg:{ex.Message}】", logType);
                            InitMessage(false, data.id.ToStringV1(), data.billNo, $"第{data.ser}行推送小满异常【FP1005】\n错误信息：{ex.Message}");
                            continue;
                        }
                    }
         
                }

               
            }
            //推送销售订单已发货金额
            {
                List<SalInvoice> saldatas = dataList.Where(x => !x.salNo.IsNullOrEmptyOrWhiteSpace()).GroupBy(x => x.salNo).Select(x => x.FirstOrDefault()).ToList();
                if (saldatas!=null)
                {
                    headers = new Dictionary<string, string>();
                    headers.Add("Authorization", $@"Bearer {TokenObj.token}");
                    string fhurl = "https://api-sandbox.xiaoman.cn/v1/invoices/order/push";
                    foreach (SalInvoice salobj in saldatas)
                    {
                        try
                        {
                            JObject MainObj = new JObject();
                            MainObj["order_id"] = salobj.salXMId;
                            //已发货金额
                            MainObj["41949423537994"] = salobj.deliveredAmount;
                            string json = MainObj.ToStringV1();

                            string inContent = $"【推送已发货金额】【{salobj.salNo}】【地址：{fhurl}】\n【header:{JsonConvert.SerializeObject(headers)}】\n【传入内容：{json}】";
                            LogHelper.XiaoManLog(inContent, logType);
                            string reponse = PostHelper.Post(fhurl, json, headers);
                            string outContent = $"【推送已发货金额】【{salobj.salNo}】【金额：{salobj.deliveredAmount}】【返回内容：{reponse}】";
                            LogHelper.XiaoManLog(outContent, logType);
                            
                        }
                        catch (Exception ex)
                        {
                            LogHelper.XiaoManLog($"异常【FH1005】【推送已发货金额】【单号：{salobj.salNo} 【金额：{salobj.deliveredAmount}】\n【msg:{ex.Message}】", logType);
                            continue;
                        }
                        
                    } 
                }
           
            }


        }

        public void InitMessage(bool status,string id,string no,string msg)
        {
            this.OperationResult.IsShowMessage = true;
            OperateResult operate = new OperateResult()
            {
                SuccessStatus = true,
                PKValue = id,
                Number = no,
                Message = msg,
            };
            this.OperationResult.OperateResult.Add(operate);
        }

    }
}
